package codeMaker;

import java.awt.*;
import java.io.File;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JLabel;

import constant.Constant;
import util.HttpDownloadUtil;
import util.ZipUtils;

public class UtilDownLoad extends JFrame {

	private JFrame frame;

	public static volatile boolean downFlag;

	/**
	 * Launch the application.
	 */
	public static void main(String url, String downLoadDir, String consoleLine) {
		UtilDownLoad window = new UtilDownLoad();
		window.frame.setVisible(true);
		try {
			String fileFullName = url.substring(url.lastIndexOf("/") + 1);
			File file = new File(downLoadDir + fileFullName);
			if (!file.exists()) {
				HttpDownloadUtil.downloadFile(url, downLoadDir);
				if (consoleLine != null) {
					ZipUtils.unZip(new File(downLoadDir + fileFullName), downLoadDir, Constant.ZIP_PWD);
				}
			}

			if (consoleLine == null) {
				//更新下载标记为true
				downFlag = true;
				window.frame.dispose();
				return;
			}
			Process process = Runtime.getRuntime().exec(consoleLine);
			// 运行实用工具
			window.frame.dispose();
			process.waitFor();
		} catch (Exception e) {
			window.frame.dispose();
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * Create the application.
	 */
	private UtilDownLoad() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setIconImage(Toolkit.getDefaultToolkit()
				.getImage(UtilDownLoad.class.getResource("/javax/swing/plaf/metal/icons/ocean/hardDrive.gif")));
		frame.setResizable(false);
		frame.setBounds(100, 100, 528, 162);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		JLabel lblNewLabel = new JLabel("正在拉取，请耐心等待。。。");
		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING,
				groupLayout.createSequentialGroup().addContainerGap(72, Short.MAX_VALUE)
						.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 405, GroupLayout.PREFERRED_SIZE)
						.addGap(45)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
				.createSequentialGroup().addGap(38).addComponent(lblNewLabel).addContainerGap(71, Short.MAX_VALUE)));
		frame.getContentPane().setLayout(groupLayout);

	}
}
